import 'dart:convert';
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mind_your_tasks/models/Event.dart';
import 'package:mind_your_tasks/models/Task.dart';
import 'package:mind_your_tasks/models/User.dart';
import 'package:mind_your_tasks/screens/event/add_event.dart';
import 'package:mind_your_tasks/screens/event/event_home_page.dart';
import 'package:mind_your_tasks/storage_utils.dart';
import 'package:mind_your_tasks/theme/colors/light_colors.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:mind_your_tasks/widgets/task_column.dart';
import 'package:mind_your_tasks/widgets/active_project_card.dart';
import 'package:mind_your_tasks/widgets/top_container.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  User user;
  List<Event> events;
  List<Event> activeEvents;
  List<Task> userTasks;
  var completedTasks = 0;
  var activeTasks = 0;
  var pendingTasks = 0;
  AddEventPage eventPage = AddEventPage();

  @override
  void initState() {
    super.initState();
  }

  setTasks(List<Event> events) {
    userTasks = [];
    completedTasks = 0;
    activeTasks = 0;
    pendingTasks = 0;
    events.forEach((event) {
      List<Task> allTasks = event.tasks;
      allTasks.forEach((task) {
        if (task.user != null && task.user.username == user.username) {
          userTasks.add(task);
          if (task.status == Status.COMPLETED)
            completedTasks++;
          else if (task.status == Status.ACTIVE)
            activeTasks++;
          else
            pendingTasks++;
        }
      });
    });
  }

  setInitStuff() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    User user = User("TestUser", "test-email@gmail.com");
    Task task = Task("Make Mockup",
        DateTime.fromMillisecondsSinceEpoch(1625077149), null, "");
    task.status = Status.COMPLETED;
    Task task2 = Task(
        "Make PPT",
        DateTime.fromMillisecondsSinceEpoch(1625077149),
        user,
        "SOMETHING TO DO");
    task2.status = Status.COMPLETED;

    Task task3 = Task(
        "Prototype",
        DateTime.fromMillisecondsSinceEpoch(1625077149),
        user,
        "SOMETHING ELSE");
    task3.status = Status.ACTIVE;

    Task task4 = Task(
        "Buy Food",
        DateTime.fromMillisecondsSinceEpoch(1625077149),
        user,
        "Burgers, chips, mayo ...");
    Task task5 = Task(
        "Buy Alcol",
        DateTime.fromMillisecondsSinceEpoch(1625077149),
        user,
        "Wine, Beer ...");
    Task task6 = Task("Bring Chairs",
        DateTime.fromMillisecondsSinceEpoch(1625077149), user, "");

    Event event = Event("Party night",
        DateTime.fromMillisecondsSinceEpoch(1625077149000), [user]);
    event.ended = true;

    event.addTask(task4);
    event.addTask(task5);
    event.addTask(task6);

    List<String> devents = [];
    devents.add(json.encode(event));

    await prefs.setString("TestUser", json.encode(user));
    await prefs.setStringList("Events", devents);
    this.user = await StorageUtils.getUser("TestUser");
    this.events = await StorageUtils.getEvents();

    this.activeEvents = [];
    events.forEach((element) {
      if (!element.ended) activeEvents.add(element);
    });
    // debugPrint(events.length.toString());
    setTasks(activeEvents);
  }

  Future<String> getData(String username) async {
    try {
      this.user = await StorageUtils.getUser(username);
      this.events = await StorageUtils.getEvents();
      this.activeEvents = [];
      events.forEach((element) {
        if (!element.ended) activeEvents.add(element);
      });
      // debugPrint(events.length.toString());
      setTasks(activeEvents);
    } catch (e) {
      setInitStuff();
    }
    // this.activeEvents = [];
    // events.forEach((element) {
    //   if (!element.ended) activeEvents.add(element);
    // });
    // debugPrint(events.length.toString());
    // setTasks(activeEvents);
    return "ready";
  }

  @override
  Widget build(BuildContext context) => FutureBuilder(
        initialData: true,
        future: getData("TestUser"),
        builder: (context, snapshot) =>
            snapshot.connectionState == ConnectionState.done && snapshot.hasData
                ? _buildWidget(context, snapshot.data)
                : const SizedBox(),
      );

  Widget _buildWidget(BuildContext context, dynamic data) {
    double width = MediaQuery.of(context).size.width;
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: LightColors.kDarkYellow,
      systemNavigationBarColor: Colors.black45,
    ));
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(30.0),
        child: AppBar(
          backgroundColor: LightColors.kDarkYellow,
          iconTheme: IconThemeData(color: Colors.black),
          elevation: 0,
        ),
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            TopContainer(
              height: 120,
              width: width,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 0, vertical: 0.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: LightColors.kBlue.withOpacity(0),
                          radius: 35.0,
                          backgroundImage: AssetImage(
                            'assets/images/avatar.png',
                          ),
                        ),
                        SizedBox(width: 20),
                        Container(
                          child: Text(
                            '磁石事项',
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              fontSize: 22.0,
                              color: Colors.white,
                              fontWeight: FontWeight.w800,
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      color: Colors.transparent,
                      padding: EdgeInsets.symmetric(
                          horizontal: 20.0, vertical: 10.0),
                      child: Column(
                        children: <Widget>[
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              subheading('全部事项'),
                            ],
                          ),
                          SizedBox(height: 15.0),
                          TaskColumn(
                            icon: Icons.alarm,
                            iconBackgroundColor: LightColors.kRed,
                            title: '待办中',
                            subtitle: '$pendingTasks 个事项',
                          ),
                          SizedBox(
                            height: 15.0,
                          ),
                          TaskColumn(
                            icon: Icons.replay,
                            iconBackgroundColor: LightColors.kDarkYellow,
                            title: '未完成',
                            subtitle: '$activeTasks 个事项',
                          ),
                          SizedBox(height: 15.0),
                          TaskColumn(
                            icon: Icons.check,
                            iconBackgroundColor:
                                Color.fromRGBO(67, 147, 31, 0.6),
                            title: '已完成',
                            subtitle: '$completedTasks 个事项',
                          ),
                        ],
                      ),
                    ),
                    Container(
                      color: Colors.transparent,
                      padding:
                          EdgeInsets.symmetric(horizontal: 20.0, vertical: 0.0),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          subheading('全部事件'),
                          GestureDetector(
                            onTap: () {
                              _onAddEvent(context);
                            },
                            child: addIcon(),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      color: Colors.transparent,
                      padding: EdgeInsets.symmetric(
                          horizontal: 20.0, vertical: 10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children:
                            activeEvents != null && activeEvents.length > 0
                                ? build_active_events()
                                : build_no_events(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> build_no_events() {
    return [
      Padding(
        padding: const EdgeInsets.only(left: 5, top: 70),
        child: Text("暂无事件",
            style: TextStyle(
                color: Colors.grey,
                fontSize: 20.0,
                fontWeight: FontWeight.w500)),
      )
    ];
  }

  _onAddEvent(context) {
    var alertStyle = AlertStyle(
      animationType: AnimationType.fromRight,
      isCloseButton: true,
      isOverlayTapDismiss: false,
      descStyle: TextStyle(fontWeight: FontWeight.normal, fontSize: 15),
      animationDuration: Duration(milliseconds: 200),
      alertBorder: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20.0),
        side: BorderSide(
          color: Colors.white,
        ),
      ),
      titleStyle: TextStyle(
          color: Colors.blueAccent, fontSize: 22, fontWeight: FontWeight.w800),
    );

    Alert(
        context: context,
        style: alertStyle,
        type: AlertType.none,
        title: "建立新事件",
        content: eventPage,
        buttons: [
          DialogButton(
            onPressed: () => {
              if (eventPage.formKey.currentState.validate())
                {
                  Navigator.pop(context),
                  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                    content: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Text("创建成功",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w800))
                        ]),
                    backgroundColor: Colors.green,
                  )),
                  createEvent(eventPage),
                  setState(() {}),
                }
            },
            child: Text(
              "创建事件",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
  }

  Future<bool> createEvent(AddEventPage eventPage) async {
    String eventName = eventPage.controllerEventName.text;
    DateTime date = eventPage.controllerDate.text != ""
        ? DateTime.parse(eventPage.controllerDate.text)
        : null;

    Event event = Event(eventName, date, [user]);
    return await StorageUtils.addNewEvent(event);
  }

  List<Widget> build_active_events() {
    List<Widget> list = [];
    List<Widget> event_cards = [];
    activeEvents.forEach((event) {
      event_cards.add(build_event_card(event));
    });

    if (event_cards.length % 2 != 0)
      event_cards.add(Expanded(
        flex: 48,
        child: Container(),
      ));

    for (var i = 0; i < event_cards.length; i += 2) {
      list.add(
        Row(
          children: <Widget>[
            event_cards[i],
            Expanded(
              flex: 4,
              child: Container(),
            ),
            event_cards[i + 1]
          ],
        ),
      );
    }
    return list;
  }

  Widget build_event_card(Event event) {
    return Expanded(
      flex: 48,
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => EventHomePage(event: event)),
          );
        },
        child: generateProjectCard(LightColors.kBlue,
            calculatePercentage(event), event.name, event.date),
      ),
    );
  }

  double calculatePercentage(Event event) {
    if (event.tasks.isNotEmpty &&
        getTasks(Status.COMPLETED, event).isNotEmpty) {
      return getTasks(Status.COMPLETED, event).length / event.tasks.length;
    } else
      return 0;
  }

  List<Task> getTasks(Status status, Event event) {
    List<Task> tasks = [];
    event.tasks.forEach((task) {
      if (task.status == status) tasks.add(task);
    });
    return tasks;
  }

  Text subheading(String title) {
    return Text(
      title,
      style: TextStyle(
          color: LightColors.kDarkBlue,
          fontSize: 20.0,
          fontWeight: FontWeight.w700,
          letterSpacing: 1.2),
    );
  }

  static CircleAvatar addIcon() {
    return CircleAvatar(
      radius: 25.0,
      backgroundColor: LightColors.kBlue,
      child: Icon(
        Icons.add,
        size: 30.0,
        color: Colors.white,
      ),
    );
  }

  static ActiveProjectsCard generateProjectCard(
    color,
    donePercent,
    title,
    date,
  ) {
    return ActiveProjectsCard(
      cardColor: color,
      loadingPercent: donePercent,
      title: title,
      date: date,
    );
  }
}
